// 使用传统的方式定义类
window.RealTimeManager = class RealTimeManager {
    constructor(config = {}) {
        this.config = {
            wsUrl: config.wsUrl || 'ws://localhost:8080',
            reconnectInterval: config.reconnectInterval || 3000,
            heartbeatInterval: config.heartbeatInterval || 30000,
            updateThrottle: config.updateThrottle || 200,
            ...config
        };

        // 初始化WebSocket管理器
        this.wsManager = new WebSocketManager({
            url: this.config.wsUrl,
            reconnectInterval: this.config.reconnectInterval,
            heartbeatInterval: this.config.heartbeatInterval,
            debug: true
        });

        // 数据缓存
        this.cache = {
            stockPrices: new Map(),
            marketIndices: new Map(),
            tradingSignals: new Map()
        };

        // 更新回调
        this.updateCallbacks = {
            stockPrices: new Set(),
            marketIndices: new Set(),
            tradingSignals: new Set()
        };

        // 节流计时器
        this.throttleTimers = {
            stockPrices: null,
            marketIndices: null,
            tradingSignals: null
        };

        // 初始化
        this.initialize();
    }

    /**
     * 初始化实时数据管理
     * @private
     */
    async initialize() {
        try {
            // 连接WebSocket
            await this.wsManager.connect();

            // 订阅各类数据
            this.subscribeToStockPrices();
            this.subscribeToMarketIndices();
            this.subscribeToTradingSignals();

        } catch (error) {
            console.error('实时数据管理器初始化失败:', error);
        }
    }

    /**
     * 订阅股票价格更新
     * @private
     */
    subscribeToStockPrices() {
        this.wsManager.subscribe('stock_prices', data => {
            // 更新缓存
            data.forEach(update => {
                this.cache.stockPrices.set(update.code, update);
            });

            // 节流更新
            if (!this.throttleTimers.stockPrices) {
                this.throttleTimers.stockPrices = setTimeout(() => {
                    this.notifyUpdates('stockPrices');
                    this.throttleTimers.stockPrices = null;
                }, this.config.updateThrottle);
            }
        });
    }

    /**
     * 订阅市场指数更新
     * @private
     */
    subscribeToMarketIndices() {
        this.wsManager.subscribe('market_indices', data => {
            // 更新缓存
            data.forEach(update => {
                this.cache.marketIndices.set(update.code, update);
            });

            // 节流更新
            if (!this.throttleTimers.marketIndices) {
                this.throttleTimers.marketIndices = setTimeout(() => {
                    this.notifyUpdates('marketIndices');
                    this.throttleTimers.marketIndices = null;
                }, this.config.updateThrottle);
            }
        });
    }

    /**
     * 订阅交易信号
     * @private
     */
    subscribeToTradingSignals() {
        this.wsManager.subscribe('trading_signals', data => {
            // 更新缓存
            data.forEach(signal => {
                this.cache.tradingSignals.set(signal.id, signal);
            });

            // 立即通知（交易信号优先级较高）
            this.notifyUpdates('tradingSignals');
        });
    }

    /**
     * 通知数据更新
     * @param {string} dataType 数据类型
     * @private
     */
    notifyUpdates(dataType) {
        const callbacks = this.updateCallbacks[dataType];
        const data = Array.from(this.cache[dataType].values());

        callbacks.forEach(callback => {
            try {
                callback(data);
            } catch (error) {
                console.error(`${dataType} 更新回调执行错误:`, error);
            }
        });
    }

    /**
     * 订阅股票价格更新
     * @param {Function} callback 回调函数
     */
    onStockPricesUpdate(callback) {
        this.updateCallbacks.stockPrices.add(callback);
        // 立即触发一次当前数据
        if (this.cache.stockPrices.size > 0) {
            callback(Array.from(this.cache.stockPrices.values()));
        }
    }

    /**
     * 订阅市场指数更新
     * @param {Function} callback 回调函数
     */
    onMarketIndicesUpdate(callback) {
        this.updateCallbacks.marketIndices.add(callback);
        // 立即触发一次当前数据
        if (this.cache.marketIndices.size > 0) {
            callback(Array.from(this.cache.marketIndices.values()));
        }
    }

    /**
     * 订阅交易信号更新
     * @param {Function} callback 回调函数
     */
    onTradingSignalsUpdate(callback) {
        this.updateCallbacks.tradingSignals.add(callback);
        // 立即触发一次当前数据
        if (this.cache.tradingSignals.size > 0) {
            callback(Array.from(this.cache.tradingSignals.values()));
        }
    }

    /**
     * 取消订阅股票价格更新
     * @param {Function} callback 回调函数
     */
    offStockPricesUpdate(callback) {
        this.updateCallbacks.stockPrices.delete(callback);
    }

    /**
     * 取消订阅市场指数更新
     * @param {Function} callback 回调函数
     */
    offMarketIndicesUpdate(callback) {
        this.updateCallbacks.marketIndices.delete(callback);
    }

    /**
     * 取消订阅交易信号更新
     * @param {Function} callback 回调函数
     */
    offTradingSignalsUpdate(callback) {
        this.updateCallbacks.tradingSignals.delete(callback);
    }

    /**
     * 获取最新的股票价格
     * @param {string} stockCode 股票代码
     * @returns {Object|null} 股票价格数据
     */
    getLatestStockPrice(stockCode) {
        return this.cache.stockPrices.get(stockCode) || null;
    }

    /**
     * 获取最新的市场指数
     * @param {string} indexCode 指数代码
     * @returns {Object|null} 市场指数数据
     */
    getLatestMarketIndex(indexCode) {
        return this.cache.marketIndices.get(indexCode) || null;
    }

    /**
     * 获取最新的交易信号
     * @param {string} signalId 信号ID
     * @returns {Object|null} 交易信号数据
     */
    getLatestTradingSignal(signalId) {
        return this.cache.tradingSignals.get(signalId) || null;
    }

    /**
     * 清理缓存
     * @param {string} dataType 数据类型（可选，不指定则清理所有）
     */
    clearCache(dataType) {
        if (dataType) {
            this.cache[dataType].clear();
        } else {
            Object.values(this.cache).forEach(cache => cache.clear());
        }
    }

    /**
     * 关闭连接
     */
    close() {
        this.wsManager.close();
        // 清理所有计时器
        Object.values(this.throttleTimers).forEach(timer => {
            if (timer) {
                clearTimeout(timer);
            }
        });
    }
}